package com.gsafety.libraryktx.net.callback

import com.gsafety.library.BaseApplication
import com.gsafety.library.Net.RetrofitExt.common.SCallBack
import com.gsafety.libraryktx.base.RespBaseBean
import com.gsafety.libraryktx.expand.toast
import com.gsafety.libraryktx.util.AppUtil.exitLogin
import retrofit2.Call

/**预警系统统一封装
 * @author : lj
 * @date : 2021/1/8 15:42
 */
abstract class CommonCallBack<T>:SCallBack<RespBaseBean<T>>(){
    override fun onSuccess(result: RespBaseBean<T>) {
        if (result.code == REQUEST_SUCCESS_CODE) {
            success(result.data)
        } else if (result.code == TOKEN_FAIL_CODE || result.code == TOKEN_TIMEOUT_CODE) {
            result.message?.let {
                BaseApplication.instance?.toast(it)
            }
            exitLogin()
        } else {
            onFail(result.message)
        }
    }

    override fun onFail(call: Call<RespBaseBean<T>>, t: Throwable) {
        onFail(t.message)
    }

    abstract fun success(response: T?)

    /**
     * errorCode大于0表示服务器业务级应答码
     *
     * @param msg
     * @param errorCode
     */
    abstract fun onFail(msg: String?)


    companion object {
        /**
         * 请求成功
         */
        const val REQUEST_SUCCESS_CODE = "200"

        /**
         * 未知错误
         */
        const val UNKNOWN_ERROR_CODE = "0"

        /**
         * 无网络情况
         */
        const val NO_NET_ERROR_CODE = "-1"

        /**
         * token过期没有权限
         */
        const val TOKEN_FAIL_CODE = "501"

        /**
         * 登录超时，请重新登录
         */
        const val TOKEN_TIMEOUT_CODE = "408"
    }
}